<template>
    <el-input class="pb-4" v-model="state.key" clearable @keyup.enter="searchFile(state.key)" placeholder="请输入您要搜索的文件名">
        <template #append>
            <el-button @click.enter="searchFile(state.key)" :icon="Search" />
        </template>
    </el-input>

    <el-table :data="state.tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column prop="title" label="文件名" width="300" />
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="size" label="大小/M" width="100" />
        <el-table-column prop="url" label="URL" width="300" />
        <el-table-column prop="createAt" label="上传时间" />
        <el-table-column prop="userName" label="上传者" />
        <el-table-column label="操作" width="260">
            <template #default="scope">
                <el-button size="small" @click="viewDetail(scope.row.id)">查看</el-button>
                <el-button size="small"
                    @click="state.dialogVisible = true,state.editFileName = scope.row.title,state.fileId = scope.row.id">
                    编辑
                </el-button>
                <el-popconfirm title="你确定要删除这个吗？" @confirm="handleDelete(scope.row.id)">
                    <template #reference>
                        <!-- 默认超级管理员才可删除 or 本人 -->
                        <el-button size="small" type="danger"
                            :disabled="user.scope < 9 && user.userId != scope.row.userId">删除
                        </el-button>
                    </template>
                </el-popconfirm>
                <el-button size="small" @click="download(baseURL + scope.row.url, scope.row.title)">下载</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination class="justify-center pt-6" background layout="prev, pager, next" :total="state.total"
        :currentPage="state.page" @current-change="handleCurrentChange" />

    <el-dialog v-model="state.dialogVisible" title="编辑">
        <el-row :gutter="20">
            <span class="pb-2 text-gray-500">修改文件名：</span>
            <el-input v-model="state.editFileName" placeholder="Please input" />
        </el-row>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="state.dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="editFile(state.fileId,state.editFileName)">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { httpFiles, httpFileDelete, httpFileSearch, httpFileEdit } from '@/api/file'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import useCurrentInstance from "@/utils/useCurrentInstance"
import { baseURL } from '@/config/index'
const { proxy } = useCurrentInstance()

const user = computed(() => proxy.$store.state.user)

const router = useRouter()
const state = reactive({
    fileId: '',
    tableData: [],
    total: 0,
    page: 1,
    size: 10,
    key: '',
    dialogVisible: false,
    editFileName: ''
})

const viewDetail = (id:number)=>{
    router.push('/detail/' + id)
    proxy.$store.commit('savePage',state.page)
}

// 根据文件路径下载文件
const download = (url: string,title:string) => {
    fetch(url).then(res => res.blob().then(blob => {
        const a = document.createElement('a')
        const url = window.URL.createObjectURL(blob)
        const filename = title
        a.href = url
        a.download = filename
        a.click()
        window.URL.revokeObjectURL(url)
    }))
}

// 修改文件
const editFile = (id: string, fileName: string) => {
    httpFileEdit({ id, title: fileName }).then((res: any) => {
        if (res.code === 200) {
            state.dialogVisible = false
            ElMessage.success('修改成功')
            getFiles(state.page)
        }
    })
}

// 获取文件列表
const getFiles = (page = 1, size = 10) => {
    httpFiles({ page, size }).then((res: any) => {
        if (res.code === 200) {
            state.tableData = res.data.rows || []
            state.total = res.data.meta.count
            state.page = res.data.meta.page
        }
    })
}

// 获取文件列表
const searchFile = (key = '', page = 1, size = 10) => {
    httpFileSearch({ key: key.trim(), page, size }).then((res: any) => {
        if (res.code === 200) {
            state.tableData = res.data.rows || []
            state.total = res.data.meta.count
            state.page = res.data.meta.page
        }
    })
}

// 删除文件
const handleDelete = (id: number) => {
    httpFileDelete({id}).then((res: any) => {
        if (res.code === 200) {
            ElMessage.success('删除成功')
            getFiles(state.page)
        }
    })
}

// 改变页码
const handleCurrentChange = (page: number) => {
    getFiles(page)
}

// 初始化表格序号
const indexMethod = (index: number) => {
    return (state.page - 1) * state.size + index + 1
}

onMounted(() => {
    // 获取上一页
    const currentPage = proxy.$store.state.page || 1
    getFiles(currentPage)
})

</script>
